import json

from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from haystack.views import SearchView

from apps.jobs.models import jobs, JobCategory
from utils.myLoginView import MyLoginView
from utils.viewmixin import LoginMixin

def papapa(func):
    def temp(*args,**kwargs):

        print(args[1].headers)
        print("---------")
        return func(*args,**kwargs)


    return temp

class JobsList(View):

    def get(self, request):

        user = request.user
        querySet = jobs.objects.all()

        ret = {"data_list": [], "collect": []}
        for obj in querySet:

            ret["data_list"].append({
                "id": obj.id,
                "name": obj.jobs_name,
                "explain": obj.jobs_explain,
                "type": obj.jobs_type,
                "max_salary": obj.jobs_max_salary,
                "min_salary": obj.jobs_min_salart,
                "province": obj.jobs_province.name,
                "city": obj.jobs_city.name,
                "district": obj.jobs_district.name,
                'user': obj.jobs_user.username,
                'look_count': obj.look_count,
                "collect": obj.collect.count()
                # 'categoty': obj.jobs_categoty.name,
            })

            if user.is_authenticated:
                # print('sssssssssss')
                ret["collect"] = [obj.job.id for obj in user.collect.all()]

        return JsonResponse({'code': 0, "errmsg": 'ok', "data": ret})


class JobDetali(View):
    # 工作详情
    def get(self, request):
        #  获取参数
        id = request.GET.get("id")

        # 查询数据库
        try:
            obj = jobs.objects.filter(id=id).first()

            obj.look_count = int(obj.look_count) + 1

            obj.save()
        except Exception as e:
            print(e)
            print("=================报错")
            return JsonResponse({"code": 400, "errmsg": "重新请求"})
        # 整理数据

        ret = {
            "id": obj.id,
            "name": obj.jobs_name,
            "explain": obj.jobs_explain,
            "type": obj.jobs_type,
            "max_salary": obj.jobs_max_salary,
            "min_salary": obj.jobs_min_salart,
            "province": obj.jobs_province.name,
            "city": obj.jobs_city.name,
            "district": obj.jobs_district.name,
            'user': obj.jobs_user.username,
            'look_count': obj.look_count,
            'categoty': obj.jobs_categoty.name,
            'require': obj.jobs_require.split("=-="),
            "collect": obj.collect.count()

        }

        # 返回响应
        return JsonResponse({"code": 200, "errmsg": 'ok', "data": ret})


class JobCategoryView(View):

    def get(self, request):

        ret = cache.get('job_categoty')

        if not ret:
            try:
                datas = JobCategory.objects.all()
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, "errmsg": '请求失败'})

            ret = []
            for data in datas:
                ret.append({
                    'id': data.id,
                    'name': data.name
                })

            cache.set('job_categoty', ret, 3600 * 12)

        return JsonResponse({"code": 0, "errmsg": "ok", "data": ret})


# Todo 变更
class AddJobView(MyLoginView):
    def post(self, request):

        user = request.user

        data = json.loads(request.body)

        data['jobs_require'] = '=-='.join(data['jobs_require'])

        try:
            jobs.objects.create(**data, jobs_user=user)
        except Exception as e:
            print(e)
            return JsonResponse({'coed': 400, 'errmsg': '重新提交'})

        return JsonResponse({'coed': 200, 'errmsg': 'ok'})


class MySearchView(SearchView):
    def create_response(self):
        # 获取搜索结果
        context = self.get_context()
        data_list = []

        for job in context['page'].object_list:
            data_list.append({
                "id": job.object.id,
                "name": job.object.jobs_name,
                "explain": job.object.jobs_explain,
                "type": job.object.jobs_type,
                "max_salary": job.object.jobs_max_salary,
                "min_salary": job.object.jobs_min_salart,
                "province": job.object.jobs_province.name,
                "city": job.object.jobs_city.name,
                "district": job.object.jobs_district.name,
                'user': job.object.jobs_user.username,
                'look_count': job.object.look_count,
                "collect": job.object.collect.count(),
                "jobs_name":job.object.jobs_name,

                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count

            })
        # 拼接参数, 返回
        return JsonResponse({"code":'200','errmsg':'ok','data':data_list},safe=False)
